import datetime
import logging
import pandas as pd
from absl import app, flags

import coin.base.database.util as db_util
from coin.support.accounting.app.sync_daily_balance import (
    _gen_engine, populate_daily_estimate_snapshot)
from coin.base.datetime_util import iterate_date

FLAGS = flags.FLAGS


def _populate_data(engine, start_date, end_date):
  query_balance_sql = """
SELECT * FROM AccountBalanceIntervalHistory WHERE balance_hid IN (
  SELECT MAX(balance_hid) from AccountBalanceIntervalHistory WHERE trading_date = '%s'
  GROUP BY account_id)
"""
  for trading_date in iterate_date(start_date, end_date):
    logging.info('Running for %s' % trading_date)
    balance_df = pd.read_sql(query_balance_sql % trading_date, engine)
    populate_daily_estimate_snapshot(engine, trading_date, balance_df)


def main(argv):
  db_config = db_util.read_db_config(FLAGS.db_config)
  engine = _gen_engine(db_config)
  start_date = datetime.datetime.strptime(FLAGS.start_date, '%Y%m%d').date()
  end_date = datetime.datetime.strptime(FLAGS.end_date, '%Y%m%d').date()
  _populate_data(engine, start_date, end_date)


if __name__ == '__main__':
  flags.DEFINE_string('db_config', None, '')
  flags.DEFINE_string('start_date', None, '')
  flags.DEFINE_string('end_date', None, '')
  app.run(main)
